/**
 * @FILE:ExpressionParse.java
 * @AUTHOR:chenqiu
 * @DATE:2016年5月31日 下午4:30:36
 **/
package com.smarttest.common.beans.protolcol.plv;

import java.math.BigDecimal;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*******************************************
 * @COMPANY:北京汇通天下科技有限公司
 * @CLASS:ExpressionParse
 * @DESCRIPTION:
 * @AUTHOR:chenqiu
 * @VERSION:v1.0
 * @DATE:2016年5月31日 下午4:30:36
 *******************************************/
public class CalculateExpression {
	private static Logger log = LoggerFactory.getLogger(CalculateExpression.class);	
	private static ScriptEngineManager mgr = new ScriptEngineManager();
	private static ScriptEngine enginer = mgr.getEngineByName("js");
    public static String calcLong(long src, PlvConfig plvConfig) {
        if(null == plvConfig.getOperator()){
            return Long.toString(src);
        }
        double coefficient=plvConfig.getCoefficient();
        int precision=plvConfig.getPrecision();
        double result= src;
        switch(plvConfig.getOperator()){
        case ADD:
        	 result = src + coefficient;
        	 break;
        case MINUS:
        	 result = src - coefficient;
        	 break;
        case MULTIPLY:
        	 result = src * coefficient;
        	 break;
        case DIVIDE:
        	 result = src / coefficient;
        	 break;
        case SPECIAL:
        	try {
        		enginer.put("v", src);
				Object value=enginer.eval(plvConfig.getSpecialExpression());
				result=Double.parseDouble(value.toString());
			} catch (ScriptException e) {
				log.error("计算表达式出错："+plvConfig.toString(),e);
				e.printStackTrace();
			}
        	break;
        default:
        	log.warn("PLv 配置有误 plvConfig:{}",plvConfig);
        }
       
        return processBigDec(result,precision);
    }
    public static String processBigDec(double value,int precision){
    	if(precision==-1){//精度配置为空
    		precision=0;
    	}
    	 BigDecimal b=new BigDecimal(value);
    	 return b.setScale(precision, BigDecimal.ROUND_HALF_UP).toString();
    }
}
